//
//  BigPicViewController.m
//  RoadMaintain
//
//  Created by 岳学坤 on 2017/5/12.
//  Copyright © 2017年 岳学坤. All rights reserved.
//

#import "BigPicViewController.h"

@interface BigPicViewController ()<UIScrollViewDelegate,UIAlertViewDelegate>
{
    UIButton *deleteBtn;
    UIImageView * img;
    double  currentScale;
    UITapGestureRecognizer *tap;
    CGFloat currentWidth;
}
@property (nonatomic,strong) UIView *nav;
@property (nonatomic,strong) UILabel *tipLabel;
@property (nonatomic)  BOOL isNavHiden;
@property (nonatomic) CGSize bgSize;
@property (nonatomic,strong) NSMutableArray *imgViewArray;
@property (nonatomic,strong) NSMutableArray *scrArray;

@end

@implementation BigPicViewController
#pragma mark - Life cycle
- (void)viewWillAppear:(BOOL)animated{
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
}
- (void)viewWillDisappear:(BOOL)animated{
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleDefault];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = Bai_Color;
    [self setUI];
    [self updateBigPic];
    if([[UIScreen mainScreen] applicationFrame].size.height>[[UIScreen mainScreen] applicationFrame].size.width){
        currentWidth = IPHONE_W;
    }else{
        currentWidth = IPHONE_H;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:)name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    [self performSelector:@selector(moment) withObject:nil afterDelay:0.05];
    
}
- (void)statusBarOrientationChange:(NSNotification *)notification

{
   
    
    
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    
    if (orientation == UIInterfaceOrientationLandscapeRight||orientation ==UIInterfaceOrientationLandscapeLeft) // home键靠右
    {
        
        currentWidth = MAX(IPHONE_W, IPHONE_H);
        [self performSelector:@selector(moment) withObject:nil afterDelay:0.05];
        
    }else{
        currentWidth = MIN(IPHONE_W, IPHONE_H);
        [self performSelector:@selector(moment) withObject:nil afterDelay:0.05];
    }
    
  
    
}
- (void)moment{
    self.bgScr.contentOffset = CGPointMake(self.imgIndex*currentWidth, 0);
}
#pragma mark - Property
- (void)setImgArray:(NSMutableArray *)imgArray{
    _imgArray = [[NSMutableArray alloc]initWithCapacity:1];
    [_imgArray addObjectsFromArray:imgArray];
    
}
- (void)setImgIndex:(NSInteger)imgIndex{
    _imgIndex = imgIndex;
}
- (NSMutableArray *)imgViewArray{
    if (_imgViewArray==nil) {
        _imgViewArray = [[NSMutableArray alloc]initWithCapacity:1];
    }
    return _imgViewArray;
}
- (NSMutableArray *)deleteArray{
    if (_deleteArray == nil) {
        _deleteArray = [[NSMutableArray alloc]initWithCapacity:1];
    }
    return _deleteArray;
}
- (NSMutableArray *)scrArray{
    if (_scrArray==nil) {
        _scrArray = [[NSMutableArray alloc]initWithCapacity:1];
    }
    return _scrArray;
}

#pragma mark - UI
- (void)setUI{
    
    self.bgScr = [[UIScrollView alloc]init];
    self.bgScr.delegate = self;
    self.bgScr.pagingEnabled = YES;
    self.bgScr.backgroundColor = [PublicMethod colorWithHexString:@"#000000" andAlpha:1];;
    [self.view addSubview:self.bgScr];
    tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeNav)];
    [self.bgScr addGestureRecognizer:tap];
   
    
    [self.bgScr mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(0);
    }];
    
   
    
    
    self.nav = [[UIView alloc]init];
    self.nav.alpha = 0;
    self.nav.backgroundColor = [PublicMethod colorWithHexString:@"#323232" andAlpha:0.8];
    [self.view addSubview:self.nav];
    [self.nav mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(0);
        make.left.mas_offset(0);
        make.right.mas_offset(0);
        make.height.mas_offset(64);
    }];
    
    self.tipLabel = [[UILabel alloc]init];
    self.tipLabel.textColor = Bai_Color;
    self.tipLabel.text = [NSString stringWithFormat:@"%d/%d",self.imgIndex+1,self.imgArray.count];
    self.tipLabel.font = [UIFont systemFontOfSize:16];
    self.tipLabel.textAlignment = 1;
    [self.nav addSubview:self.tipLabel];
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.top.mas_offset(20);
    }];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    [self.nav addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(20);
        make.left.mas_offset(15);
        make.width.mas_offset(44);
        make.height.mas_offset(44);
    }];
    
    deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [deleteBtn setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
   // [deleteBtn setTitleColor:Bai_Color forState:UIControlStateNormal];
  //  [deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
    if (self.allowDelete) {
        deleteBtn.hidden = NO;
    }else{
        deleteBtn.hidden = YES;
    }
    deleteBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [deleteBtn addTarget:self action:@selector(deletePic) forControlEvents:UIControlEventTouchUpInside];
    [self.nav addSubview:deleteBtn];
    [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(20);
        make.right.mas_offset(-10);
        make.width.mas_offset(44);
        make.height.mas_offset(44);
    }];
}
#pragma mark - UI Response
- (void)pop{
    [self dismissViewControllerAnimated:YES completion:^{
        if ([self.delegate respondsToSelector:@selector(bigPicDelegateWithImgArray:deleteArray:)]) {
        [self.delegate bigPicDelegateWithImgArray:self.imgArray deleteArray:self.deleteArray];
        }
    }];
}
- (void)deletePic{
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [actionSheet addAction:[UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (![self.imgArray[self.imgIndex]isKindOfClass:[UIImage class]]) {
            [self.deleteArray addObject:self.imgArray[self.imgIndex]];
        }

        [self.imgArray removeObjectAtIndex:self.imgIndex];
        if ([self.imgArray count]==0) {
            [self pop];
        }else{
        [self updateBigPic];
        if (self.imgIndex==0) {
            self.imgIndex = 0;
        }else{
            self.imgIndex = self.imgIndex-1;
            
        }
        self.tipLabel.text = [NSString stringWithFormat:@"%d/%d",self.imgIndex+1,self.imgArray.count];
        [self moment];
        }
    }]];
    if (IsPad) {
        actionSheet.popoverPresentationController.sourceView = deleteBtn;
        actionSheet.popoverPresentationController.sourceRect = CGRectMake(22,22, 1.0, 1.0);
    }else{
        [actionSheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    }
    
    [self presentViewController:actionSheet animated:YES completion:nil];
}
- (void)changeNav{
    _isNavHiden = !_isNavHiden;
    if (_isNavHiden) {
        [UIView animateWithDuration:0.2 animations:^{
            self.nav.alpha = 1;
        }];
    }else{
        [UIView animateWithDuration:0.2 animations:^{
            self.nav.alpha = 0;
        }];
    }
   
}
- (void)updateBigPic{
    [self.container removeFromSuperview];
    self.container = [UIView new];
    [self.bgScr addSubview:self.container];
    [self.container mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.bgScr);
        make.height.equalTo(self.bgScr);
    }];
    [self.imgViewArray removeAllObjects];
    [self.scrArray removeAllObjects];
    UIScrollView *scrool = nil;
    for (int i=0; i<self.imgArray.count; i++) {
        UIScrollView *scr = [[UIScrollView alloc]init];
        scr.maximumZoomScale=2.0;//最大倍率（默认倍率）
        scr.minimumZoomScale=1.0;//最小倍率（默认倍率）
        scr.decelerationRate=1.0;//减速倍率（默认倍率）
        scr.bounces = YES;
        scr.delegate=self;
        scr.autoresizingMask =UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleHeight;
        UITapGestureRecognizer *doubelGesture=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleGesture:)];
        doubelGesture.numberOfTapsRequired=2;
        [scr addGestureRecognizer:doubelGesture];
        [tap requireGestureRecognizerToFail:doubelGesture];
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(imglongTapClick:)];
        [scr addGestureRecognizer:longPress];
        [self.container addSubview:scr];
        [scr mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.container);
            make.bottom.equalTo(self.container);
            make.width.mas_equalTo(self.bgScr.mas_width);
            if(scrool){
                make.left.equalTo(scrool.mas_right).with.offset(0);
            }else{
                make.left.equalTo(self.container);
            }
        }];
        UIView * container = [UIView new];
        container.userInteractionEnabled = YES;
        [scr addSubview:container];
        [container mas_updateConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(scr);
        }];
       
        img = [[UIImageView alloc]init];
        img.userInteractionEnabled=YES;
        img.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleHeight;
        img.contentMode = UIViewContentModeScaleAspectFit;
        
        if ([self.imgArray[i] isKindOfClass:[UIImage class]]) {
            img.image = self.imgArray[i];
        }else{
            [img sd_setImageWithURL:[NSURL URLWithString:self.imgArray[i]] placeholderImage:[UIImage imageNamed:@"1"]];
        }
        [container addSubview:img];
        [img mas_updateConstraints:^(MASConstraintMaker *make) {
            make.center.mas_equalTo(scr);
        }];
        scrool = scr;
        [self.imgViewArray addObject:img];
        [self.scrArray addObject:scr];
        [container mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(img.mas_bottom);
            make.top.equalTo(img.mas_top);
            make.left.equalTo(img.mas_left);
            make.right.equalTo(img.mas_right);
        }];
    }
    [self.container mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(scrool.mas_right);
    }];
   
 
}
- (void)imglongTapClick:(UILongPressGestureRecognizer *)gesture{
    if (gesture.state == UIGestureRecognizerStateBegan) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"保存图片到手机" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    }
}

#pragma mark - Data handle

#pragma mark - Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        UIImageView *imgView = (UIImageView *)self.imgViewArray[_imgIndex];
        UIImageWriteToSavedPhotosAlbum(imgView.image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
    }
}
-(void)imageSavedToPhotosAlbum:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
    
    if(!error)
    {
      NSString*  message = @"成功保存到相册";
        [MBProgressHUD showTextHUDAddedTo:self.view Msg:message animated:YES];
    }
    else
    {
       NSString * message = [error description];
        [MBProgressHUD showTextHUDAddedTo:self.view Msg:message animated:YES];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    for (int i = 0 ; i<self.imgArray.count; i++) {
        if (self.bgScr.contentOffset.x==i*currentWidth) {
            
            self.imgIndex = i;
            self.tipLabel.text = [NSString stringWithFormat:@"%d/%d",i+1,self.imgArray.count];
        }
    }
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    if (![self.bgScr isEqual:scrollView]) {
        return self.imgViewArray[self.imgIndex];
    }else{
        return nil;
    }
}
-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
   if (![self.bgScr isEqual:scrollView]) {
        currentScale = scale;
    }
}
#pragma mark -DoubleGesture Action
-(void)doubleGesture:(UIGestureRecognizer *)sender
{
    
    //当前倍数等于最大放大倍数
    //双击默认为缩小到原图
    if (currentScale==2.0) {
        currentScale=1.0;
        [self.scrArray[_imgIndex] setZoomScale:currentScale animated:YES];
       
        return;
    }
    //当前等于最小放大倍数
    //双击默认为放大到最大倍数
    if (currentScale==1.0) {
        currentScale= 2.0;
        [self.scrArray[_imgIndex] setZoomScale:currentScale animated:YES];
       ;
    }
    
    CGFloat aveScale =1.0+(2.0-1.0)/2.0;//中间倍数
    
    //当前倍数大于平均倍数
    //双击默认为放大最大倍数
    if (currentScale>=aveScale) {
        currentScale = 2.0;
        [self.scrArray[_imgIndex] setZoomScale:currentScale animated:YES];
        
        return;
    }
    
    //当前倍数小于平均倍数
    //双击默认为放大到最小倍数
    if (currentScale<aveScale) {
        currentScale=1.0;
        [self.scrArray[_imgIndex] setZoomScale:currentScale animated:YES];
        
        return;
    }
}
@end
